package org.example.controller;

import io.minio.MinioClient;
import io.minio.StatObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.config.MinioConfig;
import org.example.service.FileService;
import org.example.service.impl.FileServiceImpl;
import org.example.utils.JsonData;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/v1/file")
@Slf4j
public class FileController {
    @Resource
    private MinioClient minioClient;

    @Resource
    private MinioConfig minioConfig;
    @Resource
    private FileService fileService;


    /*
    上传apk文件
     */
    @PostMapping("/upload-file")
    public JsonData upload(@RequestParam MultipartFile file) {
        String fileName = fileService.upload(file);
        String substring = fileName.substring(fileName.lastIndexOf("/") + 1);
        boolean isObjectExist;

        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            isObjectExist = fileService.doesObjectExist(minioClient, minioConfig.getBucketName(), substring);
            if (isObjectExist) {
                break;
            }

        }
        // 检查对象（文件）是否存在
        log.error("文件存在");
        String tempFileUrl = fileService.getTempFileUrl(fileName);
        fileService.copyRemoteFileToLocalTmpFile(fileName);
        log.info(tempFileUrl);

        return JsonData.buildSuccess(fileName);
    }

    /*
    输入框链接上传
     */
    @GetMapping("/link")
    public JsonData getLink(@RequestParam String link) {
        String fileName = fileService.linkAndUpload(link);
        return JsonData.buildSuccess(fileName);
    }

    //接收上传的二维码图片
    @PostMapping("/upload-qrcode")
    public JsonData uploadQrcode(@RequestParam MultipartFile file) {
        String url = fileService.analysisQRcode(file);
        log.info("url:{}", url);
        String fileName = fileService.appiumWithUrl(url);
        return JsonData.buildSuccess(fileName);
    }


}
